package com.yun.algorithmproblem.leetcode;

import com.yun.datastructure.linear.list.linkedlist.ListNode;

public class Leetcode61 {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 1) {
            return head;
        }
        ListNode sentinel = new ListNode(-1, head);
        ListNode end = sentinel;
        int length = 0;
        while (end.next != null) {
            end = end.next;
            length++;
        }
        if (length == k) {
            return sentinel.next;
        } else if (length < k) {
            k = k % length;
        }
        k = length - k;
        end.next = sentinel.next;
        end = sentinel;
        for (int i = 0; i < k; i++) {
            end = end.next;
        }
        ListNode start = end.next;
        end.next = null;
        sentinel.next = start;
        return sentinel.next;
    }

    public static void main(String[] args) {
        Leetcode61 obj = new Leetcode61();
        ListNode head = new ListNode(1, new ListNode(2));
        obj.rotateRight(head, 2);
    }
}
